package com.msunsoft.system.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.msunsoft.system.mybatis.model.SysUser;

@Controller
public class LoginController  {

    @RequestMapping(value = "/login")
    public ModelAndView sysLogin(HttpServletRequest request,HttpServletResponse response){
        
        ModelAndView model = new ModelAndView ();
        Subject subject = SecurityUtils.getSubject ();
        if (!subject.isAuthenticated ()) {
            model.setViewName("index/login");
        } else {
            // 登陆成功/以及已经登陆过的用户,直接跳到后台首页
            model.setViewName("index/index");
        }
        return model;
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ModelAndView preLogin(SysUser user,RedirectAttributes ra){
        ModelAndView model = new ModelAndView ();
        UsernamePasswordToken token = new UsernamePasswordToken (user.getUsername (),user.getPassword ());
        try {
            SecurityUtils.getSubject ().login (token);
            model.setViewName("index/index");
            return model;
        } catch (AuthenticationException e) {
            e.printStackTrace ();
            ra.addFlashAttribute ("loginError", "账号或密码有误.");
            ra.addFlashAttribute ("username", user.getUsername ());
            ra.addFlashAttribute ("password", user.getPassword ());
            model.setViewName("redirect:/login.action");
            return model;
        }

    }
    
}
